package com.jml.atomic;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntergerTest implements Runnable {
    private static Integer count = 1;
    private static AtomicInteger atomic = new AtomicInteger();

    @Override
    public void run() {
        while (true) {
            //int count = getCountAtomic();
            int count = getCount();
            System.out.println(count);
            if (count >= 150) {
                break;
            }
        }
    }

    public synchronized Integer getCount() {
        try {
            Thread.sleep(50);
        } catch (Exception e) {
        }
        return count++;
    }

    public Integer getCountAtomic() {
        try {
            Thread.sleep(50);
        } catch (Exception e) {
        }
        return atomic.incrementAndGet();
    }

    public static void main(String[] args) {
        AtomicIntergerTest test0001 = new AtomicIntergerTest();
        Thread t1 = new Thread(test0001);
        Thread t2 = new Thread(test0001);
        t1.start();
        t2.start();
        //AtomicIntergerTest继承Thread类
        // AtomicIntergerTest t1 = new AtomicIntergerTest();
        // AtomicIntergerTest t2 = new AtomicIntergerTest();
        // t1.start();
        // t2.start();
        //AtomicIntergerTest有多个实体类的时候 getCount方法 用同步代码块才能保证
        //如果是实现Runable接口，同步代码块和同步方法都可以
    }
}


